package com.example.shortvideobackend.service;

import com.example.shortvideobackend.entity.Video;
import com.example.shortvideobackend.entity.User;
import com.example.shortvideobackend.entity.Like;
import com.example.shortvideobackend.repository.VideoRepository;
import com.example.shortvideobackend.repository.UserRepository;
import com.example.shortvideobackend.repository.LikeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class VideoService {

    @Autowired
    private VideoRepository videoRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private LikeRepository likeRepository;

    public Video createVideo(String title, String description, String videoUrl, String thumbnail, Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        Video video = new Video();
        video.setTitle(title);
        video.setDescription(description);
        video.setVideoUrl(videoUrl);
        video.setThumbnail(thumbnail);
        video.setUser(user);
        video.setViews(0);
        video.setLikes(0);
        video.setCreatedAt(LocalDateTime.now());
        
        return videoRepository.save(video);
    }

    public List<Video> getAllVideos() {
        return videoRepository.findAll();
    }

    public Video getVideoById(Long id) {
        return videoRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("视频不存在"));
    }

    public List<Video> getVideosByUserId(Long userId) {
        return videoRepository.findByUser_Id(userId);
    }

    public void incrementViews(Long videoId) {
        Optional<Video> videoOpt = videoRepository.findById(videoId);
        if (videoOpt.isPresent()) {
            Video video = videoOpt.get();
            video.setViews(video.getViews() + 1);
            videoRepository.save(video);
        }
    }

    @Transactional
    public Video toggleLike(Long videoId, Long userId) {
        Video video = videoRepository.findById(videoId)
                .orElseThrow(() -> new RuntimeException("视频不存在"));
        
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        Optional<Like> existingLike = likeRepository.findByUserIdAndVideoId(userId, videoId);
        
        if (existingLike.isPresent()) {
            // 取消点赞
            likeRepository.delete(existingLike.get());
            video.setLikes(video.getLikes() - 1);
        } else {
            // 添加点赞
            Like like = new Like();
            like.setUser(user);
            like.setVideo(video);
            likeRepository.save(like);
            video.setLikes(video.getLikes() + 1);
        }
        
        return videoRepository.save(video);
    }

    public boolean isLikedByUser(Long videoId, Long userId) {
        return likeRepository.existsByUserIdAndVideoId(userId, videoId);
    }

    public void deleteVideo(Long videoId, Long userId) {
        Video video = videoRepository.findById(videoId)
                .orElseThrow(() -> new RuntimeException("视频不存在"));
        
        if (!video.getUser().getId().equals(userId)) {
            throw new RuntimeException("无权删除此视频");
        }
        
        videoRepository.delete(video);
    }
} 